//
//  JSSEmoticonkeyboardViewModel.swift
//  WeiBoItem
//
//  Created by jss on 16/4/27.
//  Copyright © 2016年 jss. All rights reserved.
//

import UIKit

//每一页最多有7列
let JSSEmoticonkeyboardMaxCol = 7
//每一页最多有3行
let JSSEmoticonkeyboardMaxRow = 3
//每一页显示的表情数量
let JSSEmoticonkeyboardPageEmoticonCount = JSSEmoticonkeyboardMaxCol * JSSEmoticonkeyboardMaxRow - 1

class JSSEmoticonkeyboardViewModel: NSObject {
  
    //单例
    static let EmoticonkeyboardSharedViewModel:JSSEmoticonkeyboardViewModel = JSSEmoticonkeyboardViewModel()
    
  private lazy var path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmoticon.plist")
    
    //表情的bundle
        lazy var emoticonBundle: NSBundle = {
    
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        return NSBundle(path: path)!
    
    }()
    
    //定义一个数组记录最近表情数组
    lazy var recentEmoticon:[JSSEmoticonModel] = {
    
        //从沙盒中取
        if let res = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? [JSSEmoticonModel] {
            return res
        }else{
            return [JSSEmoticonModel]()
        }
        
    }()
    
    //定义数组记录默认表情(下面方法抽取出来了)
    lazy var defaultEmoticons: [JSSEmoticonModel] = {
        
        return self.emoticonWithPath("default/info.plist")
    
//        //取到默认表情的的info.plist路径
//        let path = self.emoticonBundle.pathForResource("default/info.plist", ofType: nil)!
//        //读取字典数组
//        let dicts = NSArray(contentsOfFile: path)!
//        //初始化一个模型数组
//        var mArray:[JSSEmoticonModel] = []
//        //字典转模型
//        for value in dicts {
//            
//            let model = JSSEmoticonModel(dict: (value as! [String:AnyObject]))
//            
//            mArray.append(model)
//        }
//        //返回数组
//       return mArray
    
    }()
    
    //定义数组记录emoji表情
    lazy var emojiEmoticons:[JSSEmoticonModel] = {
      return self.emoticonWithPath("emoji/info.plist")
    
    }()
    
    //定义数组记录lxh表情
     lazy var lxhEmoticons:[JSSEmoticonModel] = {
    return self.emoticonWithPath("lxh/info.plist")
    
    }()
    
    
    //collectionView需要的数组
    lazy var allEmoticons:[[[JSSEmoticonModel]]] = {
        
        return [
            [self.recentEmoticon],
            self.emoticonPageArray(self.defaultEmoticons),
            self.emoticonPageArray(self.emojiEmoticons),
            self.emoticonPageArray(self.lxhEmoticons)
        ]
    }()
    
    
    //通过表情字符串找到对应的表情模型
    func emoticonWithChs(chs:String)->JSSEmoticonModel?{
        //遍历默认表情
        for value in defaultEmoticons {
            if value.chs == chs{
                return value
            }
        }
    
         //遍历浪小花表情
        for value in lxhEmoticons {
            if value.chs == chs {
               return value
            }
            
        }
        
        //遍历最近表情
        for value in recentEmoticon{
        
            if value.chs == chs{
               return value
            }
        }
        
        return nil
    }
        
    //保存最近表情
    func saveRencentEmoticon(emoticon: JSSEmoticonModel) {
        
        //去重复(要在添加之前去重复)
        var emoticons = allEmoticons[0][0]
       
//        for(index,value) in emoticons.enumerate() {
//            
//            if value.type == emoticon.type {
//                
//                if value.type == "1" {
//                    
//                    
//                    if value.code == emoticon.code {
//                        
//                        //表情是一样的
//                        emoticons.removeAtIndex(index)
//                    }
//                    
//                }else{
//                    
//                    //对比chs(表情描述字符串)
//                    if value.chs == emoticon.chs {
//                        emoticons.removeAtIndex(index)
//                    }
//                    
//                    
//                }
//                
//            }
//            
//        }
        
        
        //去重复的另外一种方法(尽量不要在遍历数组的时候移除元素)
        //取到重复表情数组
        let repeatEmoticon = emoticons.filter { (value) -> Bool in
            
            if value.type == emoticon.type {
                
                if value.type == "1" {
                    //表示是Emoji表情
                    return value.code == emoticon.code
                }else{
                //表示是图片表情
                    return value.chs == emoticon.chs
                
                }
    
                
            }else {
                
                return false
            }
        }
        
        //移除重复
        for value in repeatEmoticon {
            
            if let index = emoticons.indexOf(value){
                
                //把重复的表情按下标去掉
                emoticons.removeAtIndex(index)
            }
            
            
        }
        
        
        //1将传入的表情模型保存到当前的最近表情的数组里
        //self.recentEmoticon.append(emoticon)//这样添加没用
        
        //allEmoticons[0][0].insert(emoticon, atIndex: 0)
        emoticons.insert(emoticon, atIndex: 0)
        
        //2.去掉大于20个多余的表情
        while emoticons.count > 20 {
            
            emoticons.removeLast()
        }
        
        //赋值
        allEmoticons[0][0] = emoticons
        
        
        //使用归档的方法保存最近表情的数组
         //print(path) 测试归档成功
        
        NSKeyedArchiver.archiveRootObject(emoticons, toFile: path)
        

    }
    
    

    //切割表情(把108个表情切割成6页 每一页最多20个 最多7列 最多3行 最后一个位置是放删除按钮的
    private func emoticonPageArray(emoticons:[JSSEmoticonModel])->[[JSSEmoticonModel]]{
        
       //求出表情有多少页(公式)
        let pageCount = (emoticons.count - 1) / 20 + 1
        //定义返回数组
        var resultArray:[[JSSEmoticonModel]] = []
        
        //遍历截取的每一页的内容
        for i in 0..<pageCount {
            
          //从哪里开始截取(因为每页最多只能是20个表情)
            let loc = 20 * i
            //截取的长度
            var len = 20
            
            //判断是否越界
            if loc + len > emoticons.count {
                
                len = emoticons.count - loc
            }
           
            //截取出来每一页的数组
            let cArray = (emoticons as NSArray).subarrayWithRange(NSMakeRange(loc, len)) as! [JSSEmoticonModel]
            
              resultArray.append(cArray)
            
        }
         return resultArray
    }
        
    
    
    
    
    
    
    
    
    
    private func emoticonWithPath(fileName:String)->[JSSEmoticonModel] {
        
        
        //取到表情的info.plist路径
        let path = self.emoticonBundle.pathForResource(fileName, ofType: nil)!
        //读取字典数组
        let dicts = NSArray(contentsOfFile: path)!
        //初始化模型数组
        var mArray:[JSSEmoticonModel] = []
        //字典转模型
        for dict in dicts {
            
            let model = JSSEmoticonModel(dict: (dict as? [String:AnyObject])!)
            
            //设置表情对应的文件夹路径
            let foldername = (fileName as NSString).stringByDeletingLastPathComponent
            
            //print(foldername)
            model.folderName = foldername
            mArray.append(model)
        }
        //返回数组
        return mArray
        
    }
    
    
    
}
